<?php
defined('SYSPATH') or die('No direct script access.');

class Model_Ads extends Model_Base{
	
	protected $_table_name  = 'ads';
	protected $_table_names_plural = false;
	
	public function insert($dataArray){
		$fileUtil = FileUtil::Factory();
		$fileName = $fileUtil->saveFile($this->defaultImgPath());
		if ($fileName != FALSE){
			$dataArray["picture"] = $fileUtil->getFilePath($fileName);
			$dataArray["createtime"] = Date::formatted_time();
			$dataArray["updatetime"] = Date::formatted_time();
			if($this->values($dataArray)->check()){
				return $this->save();
			}
		}
		return false;
	}
	
	public function update($dataArray){
		$fileUtil = FileUtil::Factory();
		$dataArray["picture"] = $fileUtil->getFilePath($fileUtil->saveFile($this->defaultImgPath()),'picture');
		if (!empty($dataArray['picture'])){
			if ($dataArray['picture']!=$this->picture){
				if (!empty($this->picture)){
					$orginal_real_path = $this->defaultImgPath().DIRECTORY_SEPARATOR.$this->picture;
					$fileUtil->deleteFile($orginal_real_path);
				}
				$this->picture = $dataArray['picture'];
			}
		}
		$this->value=$dataArray["value"];
		$this->type=$dataArray["type"];
		$this->sort=$dataArray["sort"];
		$this->desc=$dataArray["desc"];
		$this->updatetime=Date::formatted_time();

		return $this->save();
	}
	
	protected function modelWithCondition($filters){
		$model = $this->where("status","=","A");
		if (array_key_exists("type", $filters)){
			$queryText = $this->convertToUtf8($filters["type"]);
			$model = $this->and_where("type","like","%".$queryText."%");
		}
		if (array_key_exists("position", $filters)){
			$queryText = $this->convertToUtf8($filters["position"]);
			$model = $this->and_where("position","like","%".$queryText."%");
		}
		return $model;
	}
	
	private function defaultImgPath(){
		return $_SERVER["DOCUMENT_ROOT"].DIRECTORY_SEPARATOR.Upload::$default_directory.DIRECTORY_SEPARATOR.'ads';
	}
}